# -*- coding: utf-8 -*-
# coding=utf-8
import re
import cn2an
from utils.log import logger

limit_1_key_pattern = re.compile("最大|最多|最好|最棒|最高|最厉害|最少|最小|最差|最低|排名最后")
limit_many_key_pattern = re.compile("(排名前(\\d+)|排名后(\\d+)|前(\\d+)|后(\\d+)|(\\d+)个|(\\d+)名|top(\\d+)|第(\\d+))(?!(个|年|月|日|季))")


class LimitRecognition:
    def __init__(self):
        pass

    def limit(self, query):
        """
        根据输入的query，预测其limit值
        :param query: 自然语言查询
        :return: limit值（列表形式）
        """
        try:
            limit = 0
            ques = cn2an.transform(query)  # 把汉字数字转成阿拉伯数字，例如：“二十一” -> “21”
            m = limit_1_key_pattern.search(ques)
            if m:
                limit = 1
            if limit == 0:
                m = limit_many_key_pattern.search(ques)
                if m:
                    for group in m.groups():
                        if group:
                            limit = group
            res = dict()
            if limit == 0:
                res['limit'] = []
            else:
                res['limit'] = [["LIMIT", str(limit)]]
            return res
        except Exception as err:
            logger.error("some errors happened in limit[{}]: {}".format(type(err), str(err)))
            raise
